﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Windows.Markup;

namespace SharpSoft.WPF.MarkupExtensions
{
    /// <summary>
    /// XAML标记扩展 resx标记用于在xaml中快捷访问程序集的默认资源文件。
    /// </summary>
    public class ResxExtension : MarkupExtension
    {
        public ResxExtension(string key)
        {
            this.Key = key;
        }
        public ResxExtension()
        {

        }
        /// <summary>
        /// 资源的键
        /// </summary>
        public string Key { get; set; }
        /// <summary>
        /// 默认值，在找不到资源时使用。
        /// </summary>
        public object DefaultValue { get; set; }
        public override object ProvideValue(IServiceProvider serviceProvider)
        {  
            Assembly assembly = Assembly.GetEntryAssembly();
            Type resType = null;
            foreach (var t in assembly.DefinedTypes)
            {
                if (t.Name == "Resources")
                {
                    resType = t;
                    break;
                }

            }
            if (resType == null)
            {
                return DefaultValue;
            }
            var fullname = resType.FullName;
            try
            {
                System.Resources.ResourceManager rm = new ResourceManager(fullname, assembly);
                return rm.GetObject(this.Key, null) ?? DefaultValue;

            }
            catch (Exception)
            {
                return DefaultValue;
            }
        }
    }
}
